package com.yirui.serialcomm.core.parse;

import com.yirui.serialcomm.core.domain.SerialCommPacket;
import com.yirui.serialcomm.core.domain.SimpleSerialCommPacket;
import com.yirui.serialcomm.core.domain.StreamType;
import com.yirui.serialcomm.core.util.ZipUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

/**
 * 数据按类型+内容+gzip方式进行打包与解包处理
 * @author Dujie
 * @create 2025/8/13
 * @since 1.0.0
 */
@Slf4j
public class MCPacketParser extends SimplePacketParser{

    @Override
    public SimpleSerialCommPacket decode(InputStream inputStream) throws IOException {
        byte[] buffer =  super.decode(inputStream);
        byte t = buffer[0];
        StreamType type;
        if(t == StreamType.TCP.ordinal()){
            type = StreamType.TCP;
        }else if(t == StreamType.UDP.ordinal()){
            type = StreamType.UDP;
        }else{
            throw new IOException("数据包类型:"+t+"不支持");
        }
        //解压内容
        return new SimpleSerialCommPacket(type, ZipUtils.uncompress(Arrays.copyOfRange(buffer, 1, buffer.length)));
    }

    @Override
    public byte[] encode(SerialCommPacket data) throws IOException {
        //压缩内容
        data.setData(ZipUtils.compress(data.getData()));
        return super.encode(data);
    }

    @Override
    protected void encodeDataLength(int size, ByteArrayOutputStream packet) {
        //类型+数据长度,类型占1位
        super.encodeDataLength(size+1, packet);
    }

    @Override
    protected void encodeDataType(SerialCommPacket data, ByteArrayOutputStream packet) {
        packet.write(data.getType().ordinal());
    }


}
